home *** CD-ROM | disk | FTP | other *** search
/ Atari Mega Archive 2 / Atari Mega Archive CD - Volume 2.iso / minix / up1510b.tgz / up1510b / src / commands / traverse.c < prev    next >
C/C++ Source or Header  |  1990-07-23  |  2KB  |  92 lines

  1. /* traverse - traverse a tree        Author:    Gary Perlman */
  2.  
  3. #include <sys/types.h>
  4. #include <sys/dir.h>
  5. #include <stdio.h>
  6.  
  7. #define STANDALONE
  8.  
  9. #define    DIR    FILE
  10. #define    MAXNAME (DIRSIZ+2)
  11. #define    opendir(path) fopen (path, "r")
  12. #define closedir(dirp) fclose (dirp)
  13.  
  14. struct direct *readdir(dirp)
  15. DIR *dirp;
  16. {
  17.   static struct direct entry;
  18.   if (dirp == NULL) return((struct direct *) NULL);
  19.   for (;;) {
  20.     if (fread(&entry, sizeof(struct direct), 1, dirp) == 0)
  21.         return((struct direct *) NULL);
  22.     if (entry.d_ino) return(&entry);
  23.   }
  24. }
  25.  
  26. char *strncpy();
  27.  
  28. char *namedir(entry)
  29. struct direct *entry;
  30. {
  31.   static char name[MAXNAME];
  32.   return(strncpy(name, entry->d_name, DIRSIZ));
  33. }
  34.  
  35.  
  36. #include <sys/stat.h>
  37. #define    isdir(path) (stat(path, &buf) ? 0 : (buf.st_mode&S_IFMT)==S_IFDIR)
  38.  
  39. traverse(path, func)
  40. char *path;
  41. int (*func) ();
  42. {
  43.   DIR *dirp;
  44.   struct direct *entry;
  45.   struct stat buf;
  46.   int filetype = isdir(path) ? 'd' : 'f';
  47.   (*func) (path, filetype, 0);
  48.   if (filetype == 'd') {
  49.     if (chdir(path) == 0) {
  50.         if (dirp = opendir(".")) {
  51.             while (entry = readdir(dirp)) {
  52.                 char name[MAXNAME];
  53.                 (void) strcpy(name, namedir(entry));
  54.                 if (strcmp(name, ".") && strcmp(name, ".."))
  55.                     traverse(name, func);
  56.             }
  57.             (void) closedir(dirp);
  58.         }
  59.         (void) chdir("..");
  60.     }
  61.   }
  62.   (*func) (path, filetype, 1);
  63. }
  64.  
  65. #ifdef STANDALONE
  66.  
  67. static Indent = 0;
  68. tryverse(file, type, pos)
  69. char *file;
  70. {
  71.   int in;
  72.   if (pos == 0) {
  73.     for (in = 0; in < Indent; in++) putchar('\t');
  74.     if (type == 'd') {
  75.         printf("%s/\n", file);
  76.         Indent++;
  77.     } else
  78.         puts(file);
  79.   } else if (type == 'd')
  80.     Indent--;
  81. }
  82.  
  83. main(argc, argv)
  84. char **argv;
  85. {
  86.   int tryverse();
  87.   char *root = argc > 1 ? argv[1] : ".";
  88.   traverse(root, tryverse);
  89. }
  90.  
  91. #endif
  92.